class AmountChange < ActiveRecord::Base
  belongs_to :operation
  belongs_to :amount

  validates_presence_of :operation
  validates_presence_of :amount

  after_create :add_changes_to_amount
  after_destroy :remove_changes_from_amount

  before_update :remove_changes_from_amount
  after_update :add_changes_to_amount
  
  private
  def add_changes_to_amount
    logger.debug("add_changes_to_amount")

    amount = self.amount || Amount.find(self.amount_id)
    amount.value += self.delta
    amount.save!
  end

  def remove_changes_from_amount
    logger.debug("remove_changes_from_amount")

    amount = self.amount || Amount.find(self.amount_id)
    prevDelta = self.changed_attributes['delta']
    amount.value -= prevDelta || self.delta
    amount.save!
  end
end
